<template>
  <div class="personnel-entry-exit-application bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">人员出入园管理-申请</h2>


    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchApplications" @reset="resetSearch" />
    </div>


    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">

      <el-button type="primary" @click="openAddDialog">申请</el-button>
      <el-button type="danger" @click="deleteSelected">删除</el-button>
      <!-- <button @click="openImportDialog" class="btn btn-secondary">导入</button> -->
      <el-button @click="exportData(applications, '人员申请', selectedIds)">导出</el-button>
    </div>


    <!-- Data Table -->

    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedApplications" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="STAFF_CODE" label="人员编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STAFF_NAME" label="人员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="ID_CARD" label="证件号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STAFF_GENDER" label="性别" header-align="center" align="center"></el-table-column>
        <el-table-column prop="TELEPHONE" label="联系方式" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STAFF_TYPE" label="人员类型" header-align="center" align="center"></el-table-column>
        <el-table-column prop="AFFILIATION" label="所属单位" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STAFF_POSITION" label="职位名称" header-align="center" align="center"></el-table-column>
        <!-- <el-table-column prop="AUTHORIZATION_TYPE" label="授权类型" header-align="center" align="center"></el-table-column> -->
        <!-- <el-table-column prop="SYSTEM_CODE" label="系统单号" header-align="center" align="center"> -->
        <!-- </el-table-column> -->
        <el-table-column prop="APPLICATION_STATUS" label="申请状态" header-align="center" align="center">
          <template #default="scope">
            <div :class="getStatusClass(scope.row.APPLICATION_STATUS)">
              {{ scope.row.APPLICATION_STATUS }}
            </div>

          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.APPLICATION_STATUS == '已提交'" type="primary" size="small"
              @click="editApplication(scope.row)" link>编辑</el-button>
            <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->
    <Pagination v-if="applications.length" :tableData="applications" @alltabledata="alltabledata" />

    <!-- Add/Edit Dialog -->
    <el-dialog class="dialog-from" v-model="isDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'" width="650"
      destroy-on-close align-center>
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">
            <!-- <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">系统单号：</label>
              <input type="text" id="staffCode" v-model="formData.SYSTEM_CODE" required class="input">
            </div> -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">人员编码：</label>
              <el-input type="text" id="staffCode" v-model="formData.STAFF_CODE" required class="input" />
            </div>
            <div>
              <label for="staffName" class="block text-sm font-medium text-muted-foreground">人员姓名：</label>
              <el-input type="text" id="staffName" v-model="formData.STAFF_NAME" required class="input" />
            </div>
            <div>
              <label for="idCard" class="block text-sm font-medium text-muted-foreground">证件号码：</label>
              <el-input type="text" id="idCard" v-model="formData.ID_CARD" required class="input" />
            </div>
            <div>
              <label for="staffGender" class="block text-sm font-medium text-muted-foreground">性别：</label>

              <el-select id="staffGender" v-model="formData.STAFF_GENDER" required placeholder="请选择" class="input">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </div>
            <div>
              <label for="TELEPHONE" class="block text-sm font-medium text-muted-foreground">联系方式：</label>
              <el-input type="text" id="TELEPHONE" v-model="formData.TELEPHONE" required class="input" />
            </div>
            <div>
              <label for="staffType" class="block text-sm font-medium text-muted-foreground">人员类型：</label>

              <el-select id="staffType" v-model="formData.STAFF_TYPE" required placeholder="请选择" class="input">

                <el-option label="企业内部人员" value="企业内部人员" />
                <el-option label="园区工作人员" value="园区工作人员" />
                <el-option label="承包商人员" value="承包商人员" />
                <el-option label="临时访客" value="临时访客" />
                <el-option label="应急救援人员" value="应急救援人员" />
                <el-option label="上级部门检查人员" value="上级部门检查人员" />
                <el-option label="驾驶员" value="驾驶员" />
                <el-option label="押运员" value="押运员" />
                <el-option label="其他" value="其他" />
              </el-select>
            </div>
            <div>
              <label for="AFFILIATION" class="block text-sm font-medium text-muted-foreground">所属单位：</label>
              <el-input type="text" v-model="formData.AFFILIATION" />
              <!-- <select id="staffType" v-model="formData.AFFILIATION" required class="input">
                <option label="管委会" value="管委会" />
              </select> -->
            </div>
            <div>
              <label for="staffPosition" class="block text-sm font-medium text-muted-foreground">职位名称：</label>
              <el-select id="staffType" v-model="formData.STAFF_POSITION" required placeholder="请选择" class="input">
                <el-option label="管理员" value="管理员" />
              </el-select>

            </div>

            <!-- <div>
                <label for="systemCode" class="block text-sm font-medium text-muted-foreground">系统单号：</label>
                <input type="text" id="systemCode" v-model="formData.system_code" readonly class="input bg-muted">
              </div> -->

            <div>
              <label for="staffPosition" class="block text-sm font-medium text-muted-foreground">专业：</label>

              <el-select id="staffType" v-model="formData.STAFF_MAJOR" required placeholder="请选择" class="input">
                <el-option label="管理专业" value="管理专业" />
              </el-select>
            </div>
            <!-- <div>
              <label class="block text-sm font-medium text-muted-foreground">其他证件：</label>
              <el-input type="text" v-model="formData.PAPERS" required class="input" />
            </div> -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">其他证件：</label>


              <div v-if="isEditing && formData.PAPERS != null" style="margin:10px 0">
                <el-button style="width: 75px; height: 30px;"
                  @click="uploadfile(apiBaseUrl + '/download/' + formData.PAPERS)">
                  下载查看
                </el-button>
              </div>
              <input type="file" id="importFile" @change="handleRISK_HAS" class="mt-1 block w-full">
              <!-- accept=".csv, .xlsx" -->
            </div>
          </div>
        </div>
        <!-- 其他信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>其他信息</span>
          </div>
          <div>
            <label class="block text-sm font-medium text-muted-foreground">备注：</label>
            <el-input type="text" v-model="formData.STAMP" required class="input" />
          </div>
        </div>
        <div class="mt-6 flex justify-end space-x-2">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
      </form>
    </el-dialog>
    <!--  -->
    <el-dialog class="dialog-from" v-model="isViewDialogOpen" title="预约详情" width="650" destroy-on-close align-center>


      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>基本信息</span>
      </div>
      <div class="grid grid-cols-3 gap-4">
        <div><strong>系统单号：</strong>{{ viewingItem.SYSTEM_CODE }}</div>
        <div><strong>人员编码：</strong>{{ viewingItem.STAFF_CODE }}</div>
        <div><strong>人员姓名：</strong>{{ viewingItem.STAFF_NAME }}</div>
        <div><strong>证件号码：</strong>{{ viewingItem.ID_CARD }}</div>
        <div><strong>性别：</strong>{{ viewingItem.STAFF_GENDER }}</div>
        <div><strong>联系方式：</strong>{{ viewingItem.TELEPHONE }}</div>
        <div><strong>人员类型：</strong>{{ viewingItem.STAFF_TYPE }}</div>
        <div><strong>所属单位：</strong>{{ viewingItem.AFFILIATION }}</div>
        <div><strong>职位名称：</strong>{{ viewingItem.STAFF_POSITION }}</div>
        <div><strong>专业：</strong>{{ viewingItem.STAFF_MAJOR }}</div>
        <div><strong>其他证件：</strong>
          <div style="margin:10px 0">
            <div>{{ viewingItem.PAPERS }}</div>
            <el-button style="width: 75px; height: 30px;"
              @click="uploadfile(apiBaseUrl + '/download/' + viewingItem.PAPERS)">
              下载查看
            </el-button>
          </div>
        </div>
      </div>
      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>其他信息</span>
      </div>
      <div><strong>备注：</strong>{{ viewingItem.STAMP }}</div>
      <div class="mt-6 flex justify-end space-x-2">
        <el-button @click="closeViewDialog">关闭</el-button>
      </div>

    </el-dialog>


    <!-- 添加导入对话框 -->
    <Teleport to="body">
      <div v-if="isImportDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[500px]">
          <h3 class="text-lg font-bold mb-4">导入人员出入园申请</h3>
          <input type="file" @change="handleFileUpload" accept=".xlsx, .xls, .csv" class="mb-4 block w-full text-sm text-muted-foreground
            file:mr-4 file:py-2 file:px-4
            file:rounded-full file:border-0
            file:text-sm file:font-semibold
            file:bg-primary file:text-primary-foreground
            hover:file:bg-primary/90" />
          <div class="flex justify-end space-x-2">
            <el-button @click="closeImportDialog">取消</el-button>
            <!-- <button @click="importData" class="btn btn-primary">导入</button> -->
          </div>
        </div>
      </div>
    </Teleport>
    <!--  -->

  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, getCurrentInstance } from 'vue'
import axios from 'axios'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()
import { exportData, uploadfile, checkval } from '#/utils/exportfile.js'
import { dayjs } from "element-plus"
const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/personnel-entry-exit'
})

const search = ref({
  STAFF_NAME: '',
  ID_CARD: '',
  STAFF_TYPE: '',
  APPLICATION_STATUS: ''
})
const formItems = ref([
  {
    label: '人员姓名:',
    model: 'STAFF_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '证件号码：',
    model: 'ID_CARD',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '人员类型：',
    model: 'STAFF_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '企业内部人员', value: '企业内部人员' },
      { label: '园区工作人员', value: '园区工作人员' },
      { label: '承包商人员', value: '承包商人员' },
      { label: '临时访客', value: '临时访客' },
      { label: '应急救援人员', value: '应急救援人员' },
      { label: '上级部门检查人员', value: '上级部门检查人员' },
      { label: '驾驶员', value: '驾驶员' },
      { label: '押运员', value: '押运员' },
      { label: '其他', value: '其他' },
    ],
  },
  {
    label: '申请状态：',
    model: 'APPLICATION_STATUS',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '已提交', value: '已提交' },
      { label: '未通过', value: '未通过' },
      { label: '通过', value: '通过' },
    ],
  },
])
const loading = ref(false)
const applications = ref([])
const selectAll = ref(false)
const isDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const isEditing = ref(false)
const formData = ref({
  files: []
})
const imgdata = ref([])
const viewingItem = ref(null)
const displayedApplications = ref([])
const alltabledata = (data) => {
  displayedApplications.value = data
}
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const rowKey = (row) => row.ID // 设置行的唯一标识

const selectedIds = ref([])
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const searchApplications = async () => {
  displayedApplications.value = []
  try {
    const response = await axios.get(`${apiBaseUrl.value}/application/search`, { params: search.value })

    applications.value = response.data.map(app => ({ ...app, selected: false }))
    updateSelectAllState()
  } catch (error) {
    console.error('搜索申请失败:', error)
    alert('搜索申请失败: ' + (error.response?.data?.message || error.message))
  }
}

const table = ref()
const resetSearch = () => {
  search.value = {
    STAFF_NAME: '',
    ID_CARD: '',
    STAFF_TYPE: '',
    APPLICATION_STATUS: ''
  }
  searchApplications()
}

const handleRISK_HAS = (event) => {
  formData.value.files = []
  const files = Array.from(event.target.files)
  formData.value.files = [files[0]]

}
const openAddDialog = () => {
  isDialogOpen.value = true
  isEditing.value = false

}

const closeDialog = () => {
  isDialogOpen.value = false
  formData.value = {
    files: []
  }
}

const handleSubmit = async () => {

  if (checkval(['STAFF_CODE',
    'STAFF_NAME',
    'ID_CARD',
    'STAFF_GENDER',
    'TELEPHONE',
    'STAFF_TYPE',
    'AFFILIATION'], '人员申请', formData.value)) {
    return
  }

  if (!formData.value.files) {
    alert('驾驶证不能为空')
    return
  }

  const formDataS = new FormData()
  for (const key in formData.value) {
    if (key !== 'files') {
      formDataS.append(key, formData.value[key])
    }
  }
  if (formData.value?.files) {
    formData.value.files.forEach((file, index) => {
      formDataS.append(`files[${index}]`, file)
    })
  }

  try {
    if (isEditing.value) {
      await axios.put(`${apiBaseUrl.value}/application/${formData.value.ID}`, formDataS, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })

    } else {


      await axios.post(`${apiBaseUrl.value}/application`, formDataS, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })

    }
    alert('提交成功')
    closeDialog()
    await searchApplications()
  } catch (error) {
    console.error('提交申请失败:', error)
    alert('提交申请失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {


  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(item => {
        axios.delete(`${apiBaseUrl.value}/application/${item.ID}`)

      }
      ))
      alert('删除成功')
      selectedIds.value = []

      await searchApplications()
      table.value.clearSelection()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const editApplication = (item) => {
  formData.value = {
    ...item,
    files: []
  }
  isEditing.value = true
  isDialogOpen.value = true
}

const viewDetails = async (item) => {
  viewingItem.value = item

  isViewDialogOpen.value = true

  // if (viewingItem.value.PAPERS) {
  //   const response = await axios.get(`${apiBaseUrl.value}/download/${viewingItem.value.PAPERS}`)
  //   imgdata.value.push(response.data.url)
  // }
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingItem.value = {}
}

const toggleSelectAll = () => {
  console.log('触发全选:', !selectAll.value)
  selectAll.value = !selectAll.value
  applications.value.forEach(app => {
    app.selected = selectAll.value
    console.log(`设置 ${app.ID} 的选中状态为:`, app.selected)
  })
}

const toggleItemSelection = (item) => {
  console.log('切换选中状态:', item.ID, !item.selected)
  item.selected = !item.selected
  updateSelectAllState()
}

const updateSelectAllState = () => {

  selectAll.value = applications.value.length > 0 && applications.value.every(app => app.selected)

}




const getStatusClass = (status) => {
  const classMap = {
    '已提交': 'bg-yellow-100 text-yellow-800',
    '通过': 'bg-green-100 text-green-800',
    '未通过': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

const importFile = ref(null)

const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}

const importData = () => {
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = '.xlsx, .xls, .csv'
  fileInput.style.display = 'none'

  fileInput.onchange = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = async (e) => {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const jsonData = XLSX.utils.sheet_to_json(worksheet)

      try {
        const response = await axios.post(`${apiBaseUrl.value}/import`, jsonData)
        alert(response.data.message || '导入成功')
        await searchApplications()
      } catch (error) {
        console.error('导入失败:', error)
        alert('导入失败: ' + (error.response?.data?.message || error.message))
      }
    }
    reader.readAsArrayBuffer(file)
  }

  document.body.appendChild(fileInput)
  fileInput.click()
  document.body.removeChild(fileInput)
}



function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF
  return buf
}

const isImportDialogOpen = ref(false)

const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
}

watch(applications, () => {

  updateSelectAllState()
}, { deep: true })

watch(selectAll, (newValue) => {
  // console.log('selectAll changed:', newValue)
  applications.value.forEach(app => {
    app.selected = newValue
    console.log('watch selectAll - 设置项目状态:', app.ID, app.selected)
  })
})

onMounted(() => {
  searchApplications()
})
</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.checkbox {
  @apply h-4 w-4 text-primary focus:ring-primary border-input rounded;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>

